import React, {Component} from 'react';
import {ajax, promptBox, toast} from 'nc-lightapp-front';
import {chectFormAction, setFormAttrAndValue} from '../../../../../public/functions/checkFormAction'
import './index.less'
import {saveValidate } from 'src/hrpub/common/utils/utils';
class Formview extends Component{
    constructor(props) {
        super(props);
        this.state = {
            mainForm: '',
            paramObj: '',
            step: '0',
            num: 0,
            formData: {},
            info2: null
        }
    }
    componentWillMount () {
        
    }
    // 将表单模板key值改变
    // setDataBeforeFormKey (props, paramObj) {
    //     let state = this.state
    //     if (state.num < 1) {
    //         // 改dataAfter的键名
    //         let meta = props.meta.getMeta()[paramObj['beforeForm']]
    //         let meta2 = props.meta.getMeta()[paramObj['afterForm']]
    //         meta.items.map(obj => {
    //             obj.attrcode = obj.attrcode + '_old'
    //             switch (obj.attrcode) {
    //                 case 'creator_old':
    //                     obj.visible = false
    //                     break;
    //                 case 'creationtime_old':
    //                     obj.visible = false
    //                     break;
    //                 case 'modifier_old':
    //                     obj.visible = false
    //                     break;
    //                 case 'modifiedtime_old':
    //                     obj.visible = false
    //                     break;
    //                 default:break;
    //             }
    //         })
    //         meta2.items.map(obj => {
    //             switch (obj.attrcode) {
    //                 case 'creator':
    //                     obj.visible = false
    //                     break;
    //                 case 'creationtime':
    //                     obj.visible = false
    //                     break;
    //                 case 'modifier':
    //                     obj.visible = false
    //                     break;
    //                 case 'modifiedtime':
    //                     obj.visible = false
    //                     break;
    //                 default:break;
    //             }
    //         })
    //     }
    //     this.setState({
    //         num: ++this.state.num
    //     })
    // }
    // 查询变更之前的数据
    initFormDataShow (paramObj) {
        let props = this.props
        let { form, button, fromApprove } = props
        // this.setDataBeforeFormKey(props, paramObj)
        let dataObj = {
            // pk_psndoc_sub: paramObj.pk_psndoc_sub,
            areaCode: paramObj.mainForm + ',' + paramObj.beforeForm  + ',' + paramObj.afterForm,
            pk_org: paramObj.pk_org,
            pageCode: paramObj.pageCode,
            appCode: paramObj.appCode,
            pk_ctrtmng: paramObj.pk_ctrtmng
        }
        // this.props.button.setButtonVisible(['edit','delete','history','revoke','submit','refresh','save','cancel','query'],false);
        ajax({
            url: '/nccloud/hrcm/ctrtmng/CtrtMngQueryDetailAction.do',
            data: dataObj,
            success: (result) => {
                if (result.success) {
                    if (!result.data) {
                        return false
                    }
                    let data = result.data;
                    let values = data.baseForm[paramObj['mainForm']].rows[0].values;
                    let formData = {rows: [{values}]};
                    let approve_state = values.approve_state.value;
                    let id = values.pk_ctrtmng.value;
                    let signtype = values.signtype.value;
                    let sign_state = values.sign_state.value;
                    
                    props.setRecord({values: {pk_ctrtmng: {value: id}}})
                    this.setState({
                        formData,
                        mainForm: paramObj['mainForm'],
                        paramObj
                    }, function () {
                        let attrMap = data.attrMap
                        let valueMap = data.valueMap
                        setFormAttrAndValue(attrMap, valueMap, props, paramObj['mainForm'], [paramObj['mainForm'], paramObj['afterForm']]) 
                        // debugger
                        form.setAllFormValue({[paramObj['mainForm']]: formData})
                    })
                    if( fromApprove ){ //来自审批中心的进行中和提交态
                        if( approve_state === '2' || approve_state === '3' ){
                            button.setButtonVisible({
                                edit: true,
                                add: false,
                                submit: false,
                                query: false,
                                delete: false,
                                launch: false,
                                history: false,
                                revoke: false,
                                refresh: false,
                                export_excel: false,
                                cardview: true,
                                output: false
                            });
                        }else{
                            button.setButtonVisible(['add', 'edit', 'submit', 'query', 'delete', 'launch', 'history', 'revoke', 'refresh', 'output', 'export_excel'], false);
                        }
                    }else{
                        //根据单据状态判断肩部按钮的显示
                        if (paramObj.isEdit) {
                            this.setMainFormEdit()
                        }else{
                            console.log("approve_state:::::::::::::",approve_state);
                             //根据单据状态判断肩部按钮的显示
                            if(approve_state === '-1'){ //自由态
                                button.setButtonVisible(['add', 'edit', 'submit', 'delete', 'refresh', 'cardview'], true);
                                button.setButtonVisible([ 'history', 'query', 'revoke' ], false);
                            }else if(approve_state === '2' || approve_state === '3'){ //进行中和提交态
                                button.setButtonVisible(['add', 'history', 'revoke', 'refresh', 'cardview'], true);
                                button.setButtonVisible(['edit', 'query', 'submit', 'delete'], false);
                            }else if(approve_state === '0' || approve_state === '1'){
                                // button.setButtonVisible(['edit', 'revoke', 'query', 'submit', 'delete'], false);
                                // button.setButtonVisible(['add', 'history', 'refresh'], true);
                                button.setButtonVisible({
                                    edit: false,
                                    revoke: false,
                                    query: false,
                                    submit: false,
                                    delete: false,
                                    add: true,
                                    history: true,
                                    refresh: true,
                                    cardview: true
                                })
                            }
                                //判断是否电子合同且状态为4时显示发起操作
                            if( signtype === '2' && sign_state === '4'){
                                button.setButtonVisible(['launch'], true);
                            }else{
                                button.setButtonVisible(['launch'], false);
                            }
                        }
                    }
                }
            }
        })
    }
    // 将主表单设置为编辑态
    setMainFormEdit () {
        let {form} = this.props
        let state = this.state
        let mainForm = state.mainForm
        form.setFormStatus(mainForm, 'edit')
    }
    // 将表格的数据重置为原来的
    resetMainFormData () {
        let {form} = this.props
        let paramObj = this.state.paramObj
        form.setAllFormValue({[paramObj['mainForm']]: this.state.formData})
        form.setFormStatus(paramObj['mainForm'], 'browse')
    }
    // 修改保存接口
    editInfoToSaveOrTakeEffect () {
        let props = this.props
        let state = this.state
        let paramObj = this.state.paramObj
        let {form, json, cardPagination, pageid, fromApprove} = props;
        if (!form.isCheckNow(paramObj['mainForm'], 'warning')) {
            return false
        }
        saveValidate(props, pageid, 'dataBase', ['dataBefore', 'dataAfter'] , 'extcard').then(() => {
            let allFormValues = form.getAllFormValue(paramObj['mainForm']).rows[0].values
            let afterFormValues = {}
            for (let key in allFormValues) {
                if (key.indexOf('_old') === -1) {
                    afterFormValues[key] = allFormValues[key]
                }
            }

            let dataObj = {
                baseParam: {step: this.state.step, pageType: 'card', info2: state.info2},
                scene : fromApprove ? 'approvesce' : null,
                formData: {
                    model: {
                        rows: [
                            {
                                values: afterFormValues,
                                status: '1'
                            }
                        ]
                    }
                }
            }
            ajax({
                url: '/nccloud/hrcm/ctrtmng/CtrtMngUpdateSaveDataAction.do',
                data: dataObj,
                success: (result) => {
                    if (result.success) {
                        let data = result.data;
                        if( !!data ){
                            this.setState({
                                step: result.data.step,
                                info2: result.data.info2
                            })
                            let title = json['cm6011-000043'] // 确认继续
                            if (result.data.step == '1') {
                                this.saveAfterTips(result.data.msg, title)
                            } else {
                                toast({
                                    color: 'success',
                                    content: json['cm6011-000005'] // 生效成功
                                })
                                form.setFormStatus(paramObj['mainForm'], 'browse')
                                // this.props.setBtnVisibleAndDisable('notShowSaveAndCancel')
                                // title = json['cm6011-000121'] // 确认生效
                                if(!fromApprove){
                                    this.props.setCardPaginationConDis(true)
                                }
                                this.props.refreshOpreation();
                                this.setState({
                                    step: '0'
                                })
                                // this.props.refreshTableList()
                            }
                        }
                    }
                },
                error: (err) => {
                    this.props.refreshOpreation()
                    toast({
                        color: 'danger',
                        content: err.message
                    })
                    form.setFormStatus(paramObj['mainForm'], 'browse');
                    throw err
                }
            })
        })
    }
    // 点击修改保存成功之后的提示
    saveAfterTips (message, title) {
        let json = this.props.json
        promptBox({
            color: 'warning',
            title: title, // 确认继续
            content: message,
            noFooter: false,
            noCancelBtn: false,
            beSureBtnName: json['cm6011-000057'], // 是
            cancelBtnName: json['cm6011-000058'], // 否
            beSureBtnClick: this.editInfoToSaveOrTakeEffect.bind(this),
            hasCloseBtn:false,
            cancelBtnClick: this.cancelBtnClick.bind(this)
        })
    }
    // 弹窗取消操作
    cancelBtnClick () {
        this.setState({
            step: '0'
        })
    }
    // 表单编辑后的触发函数
    onAfterEvent (props, moduleId, key, value, oldValue) {
        let { paramObj } =  this.state;
        // const { form } = props;
        // let formDataRows = form.getAllFormValue(moduleId).rows;
        // let formData = {
        //     model: {
        //         rows: formDataRows
        //     }
        // };
        let url = '/nccloud/hrcm/ctrtmng/CtrtMngFormAfterEditAction.do';
        chectFormAction(key, paramObj['mainForm'], props, [paramObj['mainForm'], paramObj['afterForm']], '60110307', '' , url)
        // ajax({
        //     url: '/nccloud/hrcm/ctrtmng/CtrtMngFormAfterEditAction.do',
        //     data: {
        //         appCode: paramObj.appCode,
        //         pageCode: paramObj.pageCode,
        //         itemCode: key,
        //         formData: formData
        //         // extendType: paramObj,   //续签方式,按统一期限进行续签=1, 统一续签到某个日期=2
        //         // isExtendPsn: false          //默认false
        //     },
        //     success: (result) => {
        //         debugger
        //     }
        // })
    }
    // 编辑FormCard前方法
    handleEditBefore(props, moduleId, key, value,data){
        if(key == 'newpk_conttext'){
            let meta = this.props.meta.getMeta();
            let pk_org = this.state.paramObj.pk_org;
            meta['dataAfter'].items.find(item => item.attrcode === key).queryCondition = function () {
                return {
                    "pk_org": pk_org,
                    "GridRefActionExt": "nccloud.web.hrcm.make.sqlbuilder.ContModelGridSqlBuilder"
                }
            };
            this.props.meta.setMeta(meta);
        }
        return true;
    }
    // 将表单清空
    EmptyAllFormValue () {
        let {form} = this.props
        let paramObj = this.state.paramObj
        form.EmptyAllFormValue(paramObj['mainForm'])
    }
    render () {
        const {form} = this.props
        let a = this.props.meta.getMeta();
        return (
            <div className="formView">
                {
                    this.state.mainForm !== '' ? form.createForm(this.state.mainForm,{
                        expandArr: [this.state.paramObj['afterForm']], // 设置关联表单某个区域展开
                        onAfterEvent: this.onAfterEvent.bind(this),
                        onBeforeEvent: this.handleEditBefore.bind(this)
                    }) : ''
                }

            </div>
        )
    }
}
export default Formview